/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.chrfra.controller;

import edu.chl.chrfra.exceptions.NonexistentEntityException;
import edu.chl.chrfra.entities.Car;
import java.util.Collection;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;

public class ProductJpaCtrl implements IJpaCtrl<Car> {

    // UserTransaction not used in non container (i.e. for now)
    private final UserTransaction utx;
    // Get from Database
    private final EntityManagerFactory emf;

    public ProductJpaCtrl(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }

    @Override
    public void create(Car t) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.persist(t);
        em.getTransaction().commit();
        em.close();
    }

    @Override
    public void destroy(Long id) throws NonexistentEntityException {

        EntityManager em = emf.createEntityManager();
        Car p = em.getReference(Car.class, id);
        em.getTransaction().begin();
        em.remove(p);
        em.getTransaction().commit();
        em.close();
        
    }

    @Override
    public void edit(Car t) throws NonexistentEntityException, Exception {
         Logger.getAnonymousLogger().log(Level.INFO, "EDIT jpaCtrl t.id="+t.getId());
           
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        Car merge = em.merge(t);
        em.getTransaction().commit();
        em.close();
         
    }

    @Override
    public Car findEntity(Long id) {
        EntityManager em = emf.createEntityManager();
        return em.find(Car.class, id);

    }

    @Override
    public Collection<Car> findEntities() {
        EntityManager em = emf.createEntityManager();
        Query query = em.createQuery("SELECT e FROM Car e");
        return query.getResultList();

    }

    @Override
    public Collection<Car> findEntities(int maxResults, int firstResult) {

        EntityManager em = emf.createEntityManager();
        Query query = em.createQuery("SELECT e FROM Car e");
        query.setFirstResult(firstResult);
        query.setMaxResults(maxResults);
        return query.getResultList();
    }

    @Override
    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    @Override
    public int getEntityCount() {
        EntityManager em = emf.createEntityManager();
        Query query = em.createQuery("SELECT e FROM Car e");
        return query.getResultList().size();
    }
}
